//
// Created by sgyt on 2020/3/27.
//
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *thread_function1(void *arg);
void *thread_function2(void *arg);
void cleanup(void *arg);


int main(int argc,char *argv[])
{
    pthread_t pid1,pid2;
    int err;
    void *resval;
    //创建线程1
    err = pthread_create(&pid1,NULL,thread_function1,NULL);
    if(err != 0)
    {
        perror("pthread_create is error\n");
        exit(EXIT_FAILURE);
    }
    //创建线程2
    err = pthread_create(&pid2,NULL,thread_function2,NULL);
    if(err != 0)
    {
        perror("pthread_create is error\n");
        exit(EXIT_FAILURE);
    }

    err = pthread_join(pid1,&resval);
    if(err != 0)
    {
        perror("pthread_join is error\n");
        exit(EXIT_FAILURE);
    }
    printf("thread 1 exit code %ld\n",(long)resval);

    err = pthread_join(pid2,&resval);
    if(err != 0)
    {
        perror("pthread_join is error\n");
        exit(EXIT_FAILURE);
    }
    printf("thread 2 exit code %ld\n",(long)resval);

    return 0;
}

void *thread_function1(void *arg)
{
    printf("thread 1 start\n");
    pthread_cleanup_push(cleanup,"thread 1 first handler");
    pthread_cleanup_push(cleanup,"thread 1 second handler");
    printf("thread 1 push complete\n");
    if(arg){
        return ((void *)1);
    }
    pthread_cleanup_pop(1);
    pthread_cleanup_pop(1);
    return ((void *)1);
}

void *thread_function2(void *arg)
{
    printf("thread 2 start\n");
    pthread_cleanup_push(cleanup,"thread 2 first handler");
    pthread_cleanup_push(cleanup,"thread 2 second handler");
    printf("thread 2 push complete\n");
    if(arg){
        return ((void *)2);
    }
    pthread_cleanup_pop(1);
    pthread_cleanup_pop(1);
    pthread_exit((void *)2);
}

void cleanup(void *arg)
{
    printf("cleanup :%s\n",(char *)arg);
}